package com.testjpa.client;

import java.util.Date;
import java.util.List;

import javax.naming.Context;
import javax.naming.NamingException;

import com.testjpa.business.IProjectRemote;
import com.testjpa.businesslogic.ProjectBean;
import com.testjpa.clientutility.JNDILookupClass;
import com.testjpa.entities.Project;

public class EJBApplicationClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		IProjectRemote bean = doLookup();

		Project p1 = new Project();
		p1.setIniDate(new Date());
		p1.setName("Project 1"+new Date().getTime());
		p1.setDescription("Banking App");

		Project p2 = new Project();
		p2.setIniDate(new Date());
		p2.setName("Project 2"+new Date().getTime());
		p2.setDescription("Insurance App");

		// 4. Call business logic
		//Saving new Projects
		bean.saveProject(p1);
		bean.saveProject(p2);

		//Find a Project
		p1.setId(7L);
		Project p3 = bean.findProject(p1);
		System.out.println(p3);

		//Retrieve all projects
		System.out.println("List of Projects:");
		List<Project> projects = bean.retrieveAllProjects();
		for(Project project : projects) {
			System.out.println(project);
		}
	}
	
	private static IProjectRemote doLookup() {
		Context context = null;
		IProjectRemote bean = null;
		try {
			context = JNDILookupClass.getInitialContext();
			String lookupName = getLookupName();
			bean = (IProjectRemote) context.lookup(lookupName);
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return bean;
	}
	
	private static String getLookupName() {
		String appName = "";
		String moduleName = "FirstJPAProject";
		String distinctName = "";
		String beanName = ProjectBean.class.getSimpleName();
		final String interfacename = IProjectRemote.class.getName();
		
		return new StringBuilder("ejb:")
						.append(appName)
						.append("/")
						.append(moduleName)
						.append("/")
						.append(distinctName)
						.append("/")
						.append(beanName)
						.append("!")
						.append(interfacename)
						.toString();
	}

}
